<template>
	<div class="point-cart-container">
    <div class="car-top" v-if="lists.length>0">
      <div class="car-top-title">
        <span class="text">兑换清单 <em class="cart-num">{{allCount}}</em></span>
        <div class="icon" @click="deleteGoods">
          <!-- <svg-icon icon-class="icon_delete" class="icon_delete" />清空 -->
          <i class="icon_delete"></i>清空
        </div>
      </div>
    </div>
    <div class="car-middle" v-if="lists.length>0">
      <div class="car-middle-wrap">
        <van-list
          v-model="loading"
          :finished="finished"
          :error.sync="error"
          :immediate-check="immediateCheck"
          error-text="请求失败，点击重新加载"
          finished-text=""
          @load="onLoad"
        >
          <van-checkbox-group v-model="result" ref="checkboxGroup" @change="changeSelect">
            <div class="" v-for="(lists_vo) in lists" :key="lists_vo.point_cart_id">
              <van-checkbox
                :name="lists_vo.point_cart_id"
                checked-color="#F42B2B"
                label-disabled
                icon-size="18px"
                class="goods-list"
                :disabled="lists_vo.ineffective==1?true:false"
              >
                <div class="car-middle-wrap-item">
                  <!-- <div class="car-checkbox">
                    <van-checkbox v-model="checked" checked-color="#F42B2B"></van-checkbox>
                  </div>-->
                  <div class="car-goods">
                    <div class="car-goods-img">
                      <a @click="JumpName('exchangeDetail',{id:lists_vo.point_exchange_id})">
                        <img
                          v-if="lists_vo.img"
                          :src="lists_vo.img.is_compress == 1 ?`${lists_vo.img.img_path}180x180`:lists_vo.img.img_path"
                          alt
                        />
                        <img
                          v-else
                          :src="defaultImg"
                          alt
                        />
                      </a>
                    </div>

                    <div class="car-goods-info">
                      <div class="title">
                        <span class="fontZiy" v-if="lists_vo.is_self_support == 1">自营</span>
                        <a @click="JumpName('exchangeDetail',{detailId:lists_vo.point_exchange_id})">{{lists_vo.title}}</a>
                      </div>
                      <div class="sku">
                        <!-- sku -->
                        <p class="goods-props" v-if="lists_vo.props">
                          <em>{{lists_vo.props}}</em>
                        </p>
                        <!-- 日期和备注 -->
                        <p
                          v-if="lists_vo.item_date"
                          style="color: #999"
                          class="item-date"
                        >日期：{{lists_vo.item_date}}</p>
                        <p class="item-demo" v-if="lists_vo.item_memo" style="color: #999">{{lists_vo.item_memo}}</p>
                        <!-- <p v-if="lists_vo.package_label">
                          <i class="onePrice">{{lists_vo.package_label}}</i>
                        </p> -->
                      </div>
                      <!-- <div class="type">
                        
                        <b v-if="lists_vo.is_miao" class="activity">限时秒杀</b>

                        <b
                          v-else-if="lists_vo.discount && lists_vo.discount != '10' && !lists_vo.package_org_price"
                          class="activity"
                          v-text="lists_vo.is_limit_discount?`限时会员${lists_vo.discount}折`:`会员${lists_vo.discount}折`"
                        ></b>

                        <b v-else-if="lists_vo.is_bargin" class="activity">砍价</b>
                        <p class="discounts" style="display: none;">
                          省 &yen;
                          <b></b>
                        </p>
                      </div> -->
                      <div class="price-add">
                        <div class="price-box">
                          <span class="price-now">{{lists_vo.points}}{{point_name}}</span>
                          <!-- <span class="price-origin fl">&yen;{{lists_vo.original_price}}</span> -->
                        </div>

                        <div class="add">
                          <!-- v-model="lists_vo.num" -->
                          <count-plug :value="lists_vo.num" :maxLimit="lists_vo.max_num" :disabled="disabled" @changeNum="changeNum(arguments,lists_vo)"></count-plug>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </van-checkbox>
            </div>
          </van-checkbox-group>
        </van-list>
        <div class="clear-ineffective" v-if="ineffectiveGoods"><div class="btn" @click="clearIneffective">清空失效宝贝</div></div>
      </div>
      <!-- <form :action="formAction" method="post" id="point-cart-form">
        <input type="hidden" name="settle_acount" value="">
        <input type="hidden" name="buy_type" value="oncart">
      </form> -->
      <div class="car-package">
        <div class="car-package-num">
          <div class="car-checkbox">
            <van-checkbox v-model="checked" checked-color="#F42B2B" icon-size="18px" @click="isSelectAll">
              <span class="check-txt">全选</span>
            </van-checkbox>
          </div>
        </div>
        <div class="car-package-price">
          <div class="price">
            <div class="price-top">
              合计:
              <span class="total">{{total}}{{point_name}}</span>
            </div>
            <!-- <div class="price-bottom">优惠：&yen;32</div> -->
          </div>
          <div class="btn">
            <div class="btn-buy red-gra-btn" @click="goBuy">兑换({{selectNum}})</div>
          </div>
        </div>
      </div>
    </div>
    <div class="no-goods" v-else-if="lists.length<=0 && finished">
      <no-goods ></no-goods>
    </div>
  </div>
</template>

<script>
  // import { mapGetters } from 'vuex'
  import Vue from 'vue'
  import { Checkbox, CheckboxGroup } from 'vant'
  Vue.use(Checkbox).use(CheckboxGroup)
  // import defaultImg from '@img/default_goods_img.jpg'
  import noGoods from './components/noGoods'
  import CountPlug from '@/components/CountPlug'
  import { scaleGoodsPrice } from '@/utils/index.js'
  import { getPointCart, delPointCart } from '@/api/user/member/memberApi'
  import Store from '@/utils/store'

  import { openPage } from '@/utils/utils'
  export default Vue.extend({
    name: 'index',
    components: {
      noGoods,
      CountPlug
    },
    data() {
      return {
        noData: {
          img: '',
          text: '暂无排名'
        },
        defaultImg: 'https://img.wifenxiao.com/h5-wfx/images/default_goods_img.jpg',
        ineffectiveGoods: false,
        ineffectiveResult: [],
        formAction: '',
        point_name: '',
        allCount: 0,
        selectNum: 0,
        total: 0,
        lists: [],
        checked: true, // 全选
        result: [],
        disabled: false,
        immediateCheck: false,
        loading: false,
        finished: false,
        error: false,
        p: 1
      }
    },
    watch: {
      result(val) {
        this.selectNum = val.length || 0
        this.totalChange()
      }
    },
    methods: {
      scaleGoodsPriceFn(price) {
        return scaleGoodsPrice(price, 'large')
      },
      init() {
        this.p = 1
        this.$loadingWrap.show()
        setTimeout(() => {
          this.$loadingWrap.close()
        }, 50000)
  
        getPointCart().then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            this.allCount = res.data.all_count
            this.point_name = res.data.point_name
            this.formAction = res.data.settlement_url
            if (res.data && res.data.lists && res.data.lists.length > 0) {
              this.lists = res.data.lists
              // 默认全选
              /* setTimeout(() => {
                // // console.log(this.$refs.checkboxGroup)
                this.$refs.checkboxGroup.toggleAll(this.checked)
              }, 1000) */
              res.data.lists.forEach(element => {
                if (element.ineffective == 1) {
                  this.ineffectiveGoods = true
                  this.ineffectiveResult.push(element.point_cart_id)
                } else {
                  this.result.push(element.point_cart_id)
                }
              })
              this.p++
              // 小程序自动加载更多
              this.onLoad()
            } else {
              this.lists = []
              this.finished = true
            }
          } else {
            this.$Error(res.msg)
          }
        })
      },
      onLoad() {
        getPointCart({ p: this.p }).then(res => {
          this.loading = false
          if (res.status == 1) {
            if (res.data && res.data.lists.length) {
              this.lists.push(...res.data.lists)
              // 如果全选是true
              if (this.checked) {
                res.data.lists.forEach(element => {
                  if (element.ineffective == 1) {
                    this.ineffectiveGoods = true
                    this.ineffectiveResult.push(element.point_cart_id)
                  } else {
                    this.result.push(element.point_cart_id)
                  }
                })
              }
              this.p++
            } else {
              this.finished = true
            }
          } else {
            this.$Error(res.msg)
          }
        }).catch(() => {
          this.error = true
        })
      },
      // 修改数量
      changeNum(arr, lists_vo) {
        const newNum = arr[0]
        const type = arr[1]
        const data = {
          type: type, // add（增加）reduce（减少）setting（设置）
          cart_id: lists_vo.point_cart_id,
          number: newNum
        }
        getPointCart(data).then(res => {
          if (res.status == 1) {
            // 修改数量请求成功后改变实际num
            lists_vo.num = newNum
            this.totalChange()
          } else {
            this.$Error(res.msg)
          }
        })
      },
      // CheckboxGroup的值改变
      changeSelect() {
        // 如果选择的个数不等于商品的个数，全选按钮false
        if (this.result.length != this.lists.length) {
          this.checked = false
        } else {
          this.checked = true
        }
      },
      // 点击全选和取消全选
      isSelectAll() {
        this.$refs.checkboxGroup.toggleAll(this.checked)
      },
      // 删除选中商品
      deleteGoods() {
        this.$loadingWrap.show()
        const cart_ids = this.result
        setTimeout(() => {
          this.$loadingWrap.close()
        }, 10000)
        const data = {
          cart_ids: cart_ids
        }
        delPointCart(data).then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            this.init()
          } else {
            this.$Error(res.msg)
          }
        })
      },
  
      // 清空失效宝贝
      clearIneffective() {
        this.$loadingWrap.show()
        const cart_ids = this.ineffectiveResult
        setTimeout(() => {
          this.$loadingWrap.close()
        }, 10000)
        const data = {
          cart_ids: cart_ids
        }
        delPointCart(data).then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            this.ineffectiveGoods = false
            this.ineffectiveResult = []
            this.init()
          } else {
            this.$Error(res.msg)
          }
        })
      },
      // 总额的变动
      totalChange() {
        let totalPoint = 0
        this.lists.forEach(element => {
          const id = element.point_cart_id
          this.result.findIndex((value) => {
            if (value == id) {
              totalPoint += element.num * element.points
            }
          })
        })
        this.total = totalPoint
      },
      // 结算
      goBuy() {
        const buyArr = []
        this.lists.forEach(element => {
          const id = element.point_cart_id
          this.result.findIndex((value) => {
            if (value == id) {
              buyArr.push({
                checkeds: id,
                num: element.num,
                sku_id: element.sku_id
              })
            }
          })
        })
        const settle_acount = JSON.stringify(buyArr)
        // $('input[name="settle_acount"]').val(settle_acount)
        // setTimeout(() => {
        //   this.$loadingWrap.close()
        // }, 10000)
        // // alert(JSON.stringify($('#point-cart-form').serializeArray()))
        // $('#point-cart-form').submit()
        const pointBuy = {
          settle_acount: settle_acount,
          buy_type: 'oncart'
        }
        Store.save('pointBuy', pointBuy)
        // TODO 小程序跳转结算
          this.$JumpPath(this, '/pointBuy')
        
      },
      JumpPath(url, data) {
        this.$JumpPath(this, url, data)
      },
      JumpName(url, data) {
        this.$JumpName(this, url, data)
      }
    },
    created() {
      this.init()
    }
  })
</script>
<style lang="scss">
@import 'src/styles/variables';
@import 'src/styles/mixin';
.point-cart-container{
  .goods-list{
    margin-bottom:20px;
    padding:0 30px;
    border-radius:20px;
    background:#fff;
  }
  .van-checkbox{
    align-items:initial;
  }
  .van-checkbox__icon{
    margin-top:100px;
  }
  .van-checkbox__label{
    flex:1;
    margin-left:16px;
  }
  //全选
  .car-checkbox{
    .van-checkbox{
      align-items:center;
    }
    .van-checkbox__icon{
      margin-top:0;
    }
  }
  
  .no-goods{
    padding-top:84px;
  }
  .car-top {
    position:fixed;
    top:0;
    // left:0;
    margin: 0 auto;
    max-width: 750px;
    width:100%;
    z-index:10;
    padding: 33px 25px;
    color: #333;
    font-size: 32px;
    line-height: 32px;
    background: #fff;
    border-radius: 0 0 20px 20px;
    .cart-num{
      margin:0 2px;
      color:#F30C23;
    }
    .icon {
      position: absolute;
      right: 25px;
      top: 50%;
      transform: translateY(-50%);
      color: #666666;
      font-size: 28px;
      line-height: 32px;
      .icon_delete{
        display:inline-block;
        width:35px;
        height:35px;
        background:url("https://img.wifenxiao.com/h5-wfx/images/icon_delete.png") no-repeat;
        background-size:100% 100%;
        // font-size: 35px;
        // font-weight: bold;
        vertical-align: -8px;
        margin-right: 5px;
      }
    }
  }
  .car-middle {
    padding:98px 0;
    &-wrap {
      padding:20px;
      &-item {
        position: relative;
        display: flex;
        flex-direction: row;
        padding: 36px 0;
        // border-bottom: 2px solid #eee;
        .car-checkbox {
          margin-right: 20px;
          margin-top: 60px;
        }
        .car-goods {
          flex: 1;
          display: flex;
          flex-direction: row;
          &-img {
            width: 180px;
            height: 180px;
            overflow: hidden;
            border-radius: 10px;
            img {
              width: 100%;
              height: 100%;
            }
          }
          &-info {
            margin-left: 20px;
            flex: 1;
            position: relative;
            .title {
              @include lineClamp();
              font-size: 26px;
              color: #333;
              line-height: 36px;
              height: 72px;
            }
            .sku {
              p{
                font-size: 24px;
                color: #999;
                line-height: 1;
              }
            }
            .type {
              display: inline-flex;
              color: #fff;
              background: $warning;
              line-height: 24px;
              border-radius: 15px;
              padding: 4px 8px;
              margin-bottom: 10px;
            }
            .price-add {
              width: 100%;
              position: absolute;
              bottom:0;
              display:flex;
              justify-content:space-between;
              align-items:center;
              .price-now{
                font-size: 28px;
                line-height: 1;
                color:#F42B2B;
              }
              // display: flex;
              // align-items: center;
              // justify-content: space-between;
              // &-origin {
              //   font-size: 24px;
              //   color: #999;
              //   text-decoration: line-through;
              //   margin-left: 10px;
              // }
              .add {
                // flex: 1;
                // position: absolute;
                // right: 20px;
                // bottom: 10px;
                // width: 250px;
              }
            }
          }
        }
      }
    }
  }
  .car-package {
    width: 100%;
    min-height:100px;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    margin: 0 auto;
    max-width: 750px;
    background: #fff;
    z-index: 20;
    padding: 11px 0;
    border-top: 1px solid #E5E5E5;
    display: flex;
    flex-direction: row;
    align-items: center;
    .check-txt {
      font-size: 28px;
      margin-left: -5px;
    }
    &-num {
      padding-left: 20px;
      // margin-top: 6px;
      span {
        line-height: 60px;
      }
      .count {
        @include alignTop;
      }
    }
    &-price {
      flex: 1;
      display: flex;
      flex-direction: row;
      align-items: center;
      .price {
        display:flex;
        flex-direction: column;
        flex: 1;
        text-align: left;
        padding-left: 37px;
        &-top {
          font-size: 32px;
          font-weight: bold;
          .total{
            color: #F42B2B;
            font-weight: 400;
          }
        }
        &-bottom {
          font-size: 24px;
          margin-top: 10px;
        }
      }
      .btn {
        // margin-top: 12px;
        margin-right: 20px;
        margin-left: 20px;
        &-buy {
          color: #fff;
          text-align: center;
          font-size: 32px;
          width:208px;
          line-height:76px;
          border-radius:38px;
        }
      }
    }
  }
  .clear-ineffective{
    width:100%;
    .btn{
      display: block;
      width: 216px;
      height: 62px;
      line-height: 58px;
      font-size:26px;
      color: #999;
      margin: 40px auto;
      border: 2px solid #dcdcdc;
      border-radius: 64px;
      text-align: center;
    }
  }
}

</style>
